package com.it.common.utils

import android.content.Context
import android.os.Environment
import java.io.File
import java.io.IOException

object FileUtils {


    //根据目录、文件名写入文件
    fun writeJsonToFile(json: String, dir: String, fileName: String) {
        val directory = File(Environment.getExternalStorageDirectory(), "hm/${dir}")
        if (!directory.exists()) {
            directory.mkdirs()
        }

        val file = File(directory, fileName)
        file.writeText(json)
    }

    // 从 assets 中读取并解析 JSON
    fun readJsonFromAssets(context: Context, subDirectory: String, filename: String): String? {
        var jsonString: String? = null
        try {
            // 打开 assets 中的文件
            val inputStream = context.assets.open("$subDirectory/$filename")
            // 读取文件内容
            jsonString = inputStream.bufferedReader().use { it.readText() }
        } catch (e: IOException) {
            e.printStackTrace()
            return null
        }

        // 解析 JSON 字符串并返回 JSONObject 对象
        return jsonString
    }

    //根据文件名获取json字符串
    fun readJsonFromFile(fileName: String): String? {
        val file = File(Environment.getExternalStorageDirectory(), "hm/${fileName}")
        if (!file.exists()) {
            return null
        }

        val jsonString = file.readText()
        return jsonString
    }
}